import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

// 布局组件
import MainLayout from './components/layout/MainLayout';

// 认证组件
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import PrivateRoute from './components/auth/PrivateRoute';

// 仪表盘组件
import AdminDashboard from './components/dashboard/AdminDashboard';
import PaymentManagerDashboard from './components/dashboard/PaymentManagerDashboard';
import EmployeeDashboard from './components/dashboard/EmployeeDashboard';

// 用户管理组件
import UserList from './components/users/UserList';
import UserEdit from './components/users/UserEdit';
import AdminAddUser from './components/users/AdminAddUser';

// 通知组件
import NotificationList from './components/notifications/NotificationList';
import CreateNotification from './components/notifications/CreateNotification';

// API配置
axios.defaults.baseURL = process.env.REACT_APP_API_URL || 'http://localhost:5002/api';

// 请求拦截器添加认证令牌
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 应用主组件
const App = () => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [unreadNotifications, setUnreadNotifications] = useState(0);

  // 检查用户是否已登录
  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          // 确保使用正确的API路径，axios.defaults.baseURL已包含/api前缀
          const res = await axios.get('/auth/me');
          setCurrentUser(res.data);
          // 获取未读通知数量
          fetchUnreadNotifications();
        } catch (err) {
          localStorage.removeItem('token');
        }
      }
      setLoading(false);
    };

    checkAuth();
  }, []);

  // 获取未读通知数量
  const fetchUnreadNotifications = async () => {
    try {
      // 确保使用正确的API路径，axios.defaults.baseURL已包含/api前缀
      const res = await axios.get('/notifications/unread/count');
      setUnreadNotifications(res.data.unreadCount);
    } catch (err) {
      console.error('获取未读通知数量失败', err);
    }
  };

  // 登录处理
  const handleLogin = async (credentials) => {
    try {
      // 保持API路径一致性，axios.defaults.baseURL已包含/api前缀
      const res = await axios.post('/auth/login', credentials);
      localStorage.setItem('token', res.data.token);
      setCurrentUser(res.data.user);
      fetchUnreadNotifications();
      return res.data;
    } catch (err) {
      throw err.response?.data || { message: '登录失败' };
    }
  };

  // 注册处理
  const handleRegister = async (userData) => {
    try {
      const res = await axios.post('/auth/register', userData);
      return res.data;
    } catch (err) {
      throw err.response?.data || { message: '注册失败' };
    }
  };

  // 登出处理
  const handleLogout = () => {
    localStorage.removeItem('token');
    setCurrentUser(null);
  };

  // 标记通知为已读
  const markAsRead = async (notificationId) => {
    try {
      await axios.patch(`/notifications/${notificationId}/read`);
      setUnreadNotifications(prev => Math.max(0, prev - 1));
    } catch (err) {
      console.error('标记通知为已读失败', err);
    }
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  return (
    <Router>
      <div className="App">
        <Routes>
          {/* 公开路由 */}
          <Route path="/login" element={currentUser ? <Navigate to="/" /> : <Login onLogin={handleLogin} />} />
          <Route path="/register" element={currentUser ? <Navigate to="/" /> : <Register onRegister={handleRegister} />} />

          {/* 受保护路由 */}
          <Route element={<PrivateRoute currentUser={currentUser} />}>
            <Route element={<MainLayout currentUser={currentUser} onLogout={handleLogout} unreadNotifications={unreadNotifications} />}>
              {/* 仪表盘路由 - 根据角色显示不同仪表盘 */}
              <Route path="/" element={
                currentUser?.role === 'admin' ? <AdminDashboard /> :
                currentUser?.role === 'payment_manager' ? <PaymentManagerDashboard /> :
                <EmployeeDashboard />
              } />

              {/* 用户管理路由 - 仅管理员 */}
              {currentUser?.role === 'admin' && (
                <>
                  <Route path="/users" element={<UserList />} />
                  <Route path="/users/:id/edit" element={<UserEdit />} />
              <Route path="/admin/add-user" element={<AdminAddUser />} />
                </>
              )}

              {/* 通知路由 */}
              <Route path="/notifications" element={<NotificationList onMarkAsRead={markAsRead} />} />

              {/* 创建通知路由 - 管理员和清算经理 */}
              {(currentUser?.role === 'admin' || currentUser?.role === 'payment_manager') && (
                <Route path="/notifications/create" element={<CreateNotification />} />
              )}
            </Route>
          </Route>

          {/* 重定向所有其他路由到首页 */}
          <Route path="*" element={<Navigate to="/" />} />
        </Routes>

        {/* Toast通知 */}
        <ToastContainer position="top-right" autoClose={3000} hideProgressBar={false} />
      </div>
    </Router>
  );
};

export default App;